package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcReportItemMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.OmcReportItem;
import com.csun.cmny.provider.model.domain.OmcServiceItem;
import com.csun.cmny.provider.service.OmcReportItemService;
import com.csun.cmny.provider.vo.ReportItemVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
@Transactional
public class OmcReportItemServiceImpl extends BaseService<OmcReportItem> implements OmcReportItemService {

    @Resource
    OmcReportItemMapper omcReportItemMapper;

    /*
    * 根据服务项id查找异常报告项
    * */
    @Override
    public List<ReportItemVo> selectByServiceItemId(Long serviceItemId) {
        return omcReportItemMapper.selectByServiceItemId(serviceItemId);
    }

    /*
    * 保存异常报告项
    * */
    @Override
    public Integer saveReportItem(OmcReportItem omcReportItem) {
        if(omcReportItem.isNew()){
            //校验异常报告内容是否相同
            if(!checkContent(omcReportItem)){
                throw new OmcBizException(ErrorCodeEnum.OMC10033004);
            }else{
                return omcReportItemMapper.insertSelective(omcReportItem);
            }
        }else{
            //校验异常报告内容是否相同
            if(!checkContent(omcReportItem)){
                throw new OmcBizException(ErrorCodeEnum.OMC10033004);
            }else{
                return omcReportItemMapper.updateByPrimaryKeySelective(omcReportItem);
            }
        }
    }

    /*
    * 校验报告内容是否相同
    * */
    public boolean checkContent(OmcReportItem omcReportItem){
        Example example = new Example(OmcReportItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("reportItemContent", omcReportItem.getReportItemContent());
        criteria.andEqualTo("serviceItemId", omcReportItem.getServiceItemId());
        if(omcReportItem.getId() != null){
            criteria.andNotEqualTo("id", omcReportItem.getId());
        }
        int result = selectCountByExample(example);
        return result<1;
    }

}
